<?php

namespace app\filters;

use app\constants\Acl;
use app\constants\Code;
use app\models\Group;
use app\services\AdminService;
use Yii;
use yii\base\ActionFilter;

/**
 * 过滤请求
 */
class AclFilter extends ActionFilter
{
    //后台动作控制
    public function beforeAction($action)
    {
        //下面三行代码开启之后，就不限制权限了，如果要限制权限请注释下面三行代码！！
        // $session['userRole'] = 'administrator';
        // if ('administrator' == 'administrator') {
        //     return true;
        // }

        $groupId      = AdminService::getLoginGroupIdFromSession();
        $groupModel   = new Group();
        $userGroup    = $groupModel->dbGet(['groupAcl'], '', ['where' => ['id' => $groupId]]);
        $loginUserAcl = $userGroup['groupAcl'];
        $currentAcl   = explode(',', $loginUserAcl);
        //如果是管理员，不用校验权限
        if ('administrator' == $loginUserAcl || $groupId == 1) {
            return true;
        }
        $acl = strtolower($action->controller->id) . '_' . strtolower($action->id);
        if ('default_index' == $acl) {
            return true;
        }//所有用户都可以访问这个页面
        //过滤非法访问  如果配置内没有的  返回错误
        $configAcl = Acl::$aclConfig;
        //获得所有的权限配置菜单
        $firstAcl  = [];
        $secondAcl = [];
        $thirdAcl  = [];
        foreach ($configAcl as $K => $v) {
            $firstAcl[] = $v['acl'];
            foreach ($v['action'] as $kk => $vv) {
                $secondAcl[] = $vv['acl'];
                foreach ($vv['list_acl'] as $kkk => $vvv) {
                    $thirdAcl[] = $vvv;
                }
            }
        }
        $allAcl = array_merge($firstAcl, $secondAcl, $thirdAcl);
        //判断是否有权限访问
        if (in_array($acl, $allAcl) && !in_array($acl, $currentAcl)) {
            //根据是否为ajax，返回错误提示信息
            if (Yii::$app->request->isAjax || (isset($_REQUEST['ajax']) && '1' == $_REQUEST['ajax'])) {
                die(json_encode([
                    'code'    => Code::ACCESS_FORBIDDEN,
                    'message' => Code::$messages[Code::ACCESS_FORBIDDEN],
                ]));
            } else {
                $action->controller->redirect(['default/forbidden']);
                //die(Code::$messages[Code::ACCESS_FORBIDDEN]);
            }
            return false;
        }
        return true; //如果返回值为false,则action不会运行
    }

    // 当前用户权限
     public static function currentAcl()
     {
         $groupId      = AdminService::getLoginGroupIdFromSession();
         $groupModel   = new Group();
         $userGroup    = $groupModel->dbGet(['groupAcl'], '', ['where' => ['id' => $groupId]]);
         $loginUserAcl = $userGroup['groupAcl'];
         $currentAcl   = explode(',', $loginUserAcl);
         return $currentAcl;
     }
}
